package com.wechat.core.bean;

import com.wechat.core.constant.enums.support.RStatus;
import com.wechat.core.exception.ServiceException;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @param <T>
 * @author pengyi
 */
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Result<T> implements Serializable {
    
    private static final long serialVersionUID = 1L;
    
    /**
     * 消息
     */
    
    private String message = RStatus.SUCCESS.getMessage();
    
    /**
     * 状态码
     */
    @ApiModelProperty("响应状态码")
    private int code = RStatus.SUCCESS.getValue();
    
    /**
     * 数据
     */
    @ApiModelProperty("响应数据")
    private T result;
    
    public Result(RStatus status) {
        this.message = status.getMessage();
        this.code = status.getValue();
    }
    
    public Result(RStatus status, String msg) {
        this.message = msg;
        this.code = status.getValue();
    }
    
    public Result(RStatus status, T result) {
        this.message = status.getMessage();
        this.code = status.getValue();
        this.result = result;
    }
    
    public Result(RStatus status, String msg, T result) {
        this.message = msg;
        this.code = status.getValue();
        this.result = result;
    }
    
    public Result(String msg, T result) {
        this.message = msg;
        this.result = result;
    }
    
    public Result(T result) {
        
        this.result = result;
    }
    
    public Result(String msg) {
        this.message = msg;
    }
    
    public Result(Throwable e) {
        this.message = e.getMessage();
        if (e instanceof ServiceException) {
            this.result = (T)((ServiceException)e).getData();
            this.code = ((ServiceException) e).getCode();
        } else {
            this.code = RStatus.FAIL.getValue();
        }
        
    }
    
    public Result<T> msg(String msg) {
        this.message = msg;
        return this;
    }
    
    public Result<T> code(int code) {
        this.code = code;
        return this;
    }
    
    public Result<T> result(T result) {
        this.result = result;
        return this;
    }
}
